import { defineStore } from 'pinia'
import { getUserEpInfo, getUserUnread, logout } from '@/api/user'
import { getEnterpriseDetail } from '@/api/asset/enterprise.js'
import { uuid } from '@/utils'
import { UserEPRes } from '../types'
import store from '../pinia'

const useUserStore = defineStore('user-info', {
  state: () => {
    return {
      token: '',
      // 用户ID
      userId: 0,
      // 员工ID
      employeeId: 0,
      // 登录账号
      userName: '',
      // 真实姓名
      realName: '',
      // 企业名称
      epName: '',
      // 企业ID
      epId: 0,
      // 企业简称（左上角）
      briefName: '',
      // logo（左上角）
      logo: '',
      // 商户配置
      enterpriseDetail: {},
      // 同步库存配置
      syncInventory: null,
      // 系统消息未读数量
      sysMsgUnreadCount: 10,
      // 业务通知未读数量
      buzMsgUnreadCount: 10,
      // 登录去解绑
      login2Unbind: false,
    }
  },
  actions: {
    setUser() {
      return new Promise((resolve) => {
        this.token = uuid()
        getUserEpInfo().then((res: UserEPRes) => {
          const { userInfo, ...epInfo } = res.result
          this.epName = epInfo.epName
          this.epId = userInfo.epId
          this.briefName = epInfo.briefName
          this.logo = epInfo.logoMini
          this.userName = userInfo.username
          this.realName = userInfo.realName
          this.userId = userInfo.userId
          this.employeeId = userInfo.employeeId
          resolve(userInfo)
        })
      })
    },
    setEpInfo(newInfo: any) {
      this.logo = newInfo.logo
      this.briefName = newInfo.briefName
    },
    setEpDetail(callback?: Function) {
      getEnterpriseDetail().then((res: any) => {
        if (res.code == 200) {
          const result = res.result
          this.enterpriseDetail = result
          callback && callback(result)
          this.syncInventory = result.config
        }
      })
    },
    isTokenExpire() {
      return !this.token
    },
    logout(fetchLogout = false) {
      return new Promise<void>((resolve) => {
        if (fetchLogout) {
          logout({}).finally(() => {
            this.$reset()
            sessionStorage.clear()
            localStorage.setItem('my_user', '')
            resolve()
          })
        } else {
          this.$reset()
          sessionStorage.clear()
          localStorage.setItem('my_user', '')
          resolve()
        }
      })
    },
    updateUnreadMsgCount() {
      getUserUnread().then((res: any) => {
        if (res.code) {
          const result = res.result || {}
          this.buzMsgUnreadCount = result.type1 || 0
          this.sysMsgUnreadCount = result.type2 || 0
        }
      })
    },
  },
  getters: {
    // 长短租业务配置
    epServiceTypes: (state) => state.enterpriseDetail.userServiceTypes,
    // 长短租业务配置是否包含短租
    epServiceIncludeShortOrder: (state) => {
      const epServiceTypes = state.epServiceTypes || []
      return epServiceTypes.includes(1)
    },
    // 长短租业务配置是否包含长租
    epServiceIncludeLongOrder: (state) => {
      const epServiceTypes = state.epServiceTypes || []
      return epServiceTypes.includes(2)
    },
    // 渠道订单同步开关
    epChannelOrderSync: (state) => state.enterpriseDetail.channelOrderSync,
    // 渠道订单维护方式
    epChannelOrderMaintenance: (state) => state.enterpriseDetail.channelOrderMaintenance,
    // 未读消息数量
    unreadCount: (state) => state.sysMsgUnreadCount + state.buzMsgUnreadCount,
    // 是否开启反向写价格
    epChannelPriceSync: (state) => {
      const config = state.enterpriseDetail?.config || {}
      return config.channelPriceSync
    },
    // 支付宝免押码是否开启
    epAlipaySwitch: (state) => {
      const config = state.enterpriseDetail?.config || {}
      return config.alipaySwitch
    },
    // 是否开启ocr识别
    epOcrSwitch: (state) => {
      const config = state.enterpriseDetail?.config || {}
      return config.ocrSwitch
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'my_user',
        storage: localStorage,
      },
    ],
  },
})

export default useUserStore

export function useUserStoreContext() {
  return useUserStore(store)
}
